package com.antstorm.statistics.service.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * mqtt消费端处理器
 */
@Component
public class MqttConsumerHandler implements MqttCallback {

    private static Logger logger= LoggerFactory.getLogger(MqttConsumerHandler.class);

    @Autowired
    private MqttMsgHandlerCore mqttMsgHandlerCore;

    @Autowired
    private MqttConsumer mqttConsumer;


    /**
     * 连接断开的处理函数
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        try {
            logger.warn(" mq - - 连接断开,开始重新连接并订阅topic!");
            mqttConsumer.subscribe();
        }catch (Exception e){
            e.printStackTrace();
            logger.info("mq - < 重新连接、订阅 > ，发生异常！");
        }

    }

    /**
     * 接收消息的处理函数
     *
     * @param s
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        // 人工制造异常来断开连接，测试是否会自动重连. 测试结果： 会重连，但是无法再接收到topic的消息. 经测试，无法接收消息的原因是重连后没有订阅topic.
        // todo: 指定出通信协议格式，再根据解析出的内容进行处理
        mqttMsgHandlerCore.getHandler(s).handle(mqttMessage);
    }


    /**
     * 消费发送完成的处理函数
     *
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info(" deliveryComplete  finish !!  [{}] " , iMqttDeliveryToken.isComplete());
    }


}
